package com.speciality.demo.demos.service.impl;

import com.speciality.demo.demos.dto.DailyChartVO;
import com.speciality.demo.demos.entity.WeatherDaily;
import com.speciality.demo.demos.mapper.WeatherDailyMapper;
import com.speciality.demo.demos.service.WeatherDailyChartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class WeatherDailyChartServiceImpl implements WeatherDailyChartService {
    @Autowired
    private WeatherDailyMapper weatherDailyMapper;

    @Override
    public DailyChartVO getDailyChartData(LocalDate startDate, LocalDate endDate) {
        List<WeatherDaily> dailyList = weatherDailyMapper.selectDailyByTimeRange(startDate, endDate);
        DailyChartVO vo = new DailyChartVO();
        List<String> xAxis = new ArrayList<>();
        List<Double> tempMax = new ArrayList<>();
        List<Double> tempMin = new ArrayList<>();
        List<Double> precipitation = new ArrayList<>();
        List<Double> windSpeed = new ArrayList<>();

        double totalPrecip = 0, avgTemp = 0;
        double maxWind = 0;
        int count = 0;

        for (WeatherDaily daily : dailyList) {
            xAxis.add(daily.getDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            tempMax.add(daily.getTemperature2mMax());
            tempMin.add(daily.getTemperature2mMin());
            precipitation.add(daily.getPrecipitationSum());
            windSpeed.add(daily.getWindspeed10mMax());

            // 统计计算
            totalPrecip += daily.getPrecipitationSum() != null ? daily.getPrecipitationSum() : 0;
            avgTemp += (daily.getTemperature2mMax() + daily.getTemperature2mMin()) / 2;
            if (daily.getWindspeed10mMax() != null && daily.getWindspeed10mMax() > maxWind) {
                maxWind = daily.getWindspeed10mMax();
            }
            count++;
        }
        if (count > 0) {
            avgTemp /= count;
        }
        vo.setXAxis(xAxis);
        vo.setTempMaxData(tempMax);
        vo.setTempMinData(tempMin);
        vo.setPrecipitationData(precipitation);
        vo.setWindSpeedData(windSpeed);
        vo.setAvgTemperature(avgTemp);
        vo.setTotalPrecipitation(totalPrecip);
        vo.setMaxWindSpeed(maxWind);

        return vo;
    }
}
